package com.fast.develop.core.context;

import com.fast.develop.core.event.ContextStartedEvent;
import com.fast.develop.core.event.ContextStoppedEvent;
import com.fast.develop.core.event.ModuleEvent;
import com.fast.develop.core.exception.ModuleContextException;
import com.fast.develop.core.listener.ModuleListener;
import com.fast.develop.core.registry.ModuleRegistry;
import com.fast.develop.meta.base.MetaConfiguration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 莫寅
 * @createTime 2022-06-07 13:22
 * @desc：
 */
public abstract class AbstractModuleContext implements ModuleContext {

    Map<Class, Object> beans = new HashMap();

    private ModuleRegistry pluginRegistry;

    private MetaConfiguration metaConfiguration;

    private boolean initialized = false;

    /**
     * 是否销毁
     */
    private boolean destroyed = false;

    public AbstractModuleContext(MetaConfiguration metaConfiguration, ModuleRegistry pluginRegistry) {
        this.pluginRegistry = pluginRegistry;
        this.metaConfiguration = metaConfiguration;
    }

    protected abstract void initialize();

    public void refresh(){
        if(initialized){
            throw new ModuleContextException("已初始化！");
        }

        initialize();
        start();

        initialized = true;
    }






    @Override
    public String getId() {
        return null;
    }

    @Override
    public String getModuleName() {
        return null;
    }

    @Override
    public <T> T getBean(Class<T> tClass) {
        return (T) beans.get(tClass);
    }


    public void destroy(){
        this.destroyed = true;

        stop();
    }

    private void start() {
        ContextStartedEvent contextStartedEvent = new ContextStartedEvent(this);
        publishEvent(contextStartedEvent);
    }

    private void stop() {
        ContextStoppedEvent contextStoppedEvent = new ContextStoppedEvent(this);
        publishEvent(contextStoppedEvent);
    }



    public void publishEvent(ModuleEvent event) {
        if(pluginRegistry == null){
            return;
        }

        List<ModuleListener> listeners = pluginRegistry.getModuleListeners(event.getClass());
        if(listeners != null){
            for (ModuleListener listener : listeners) {
                listener.onEvent(event);
            }
        }

    }



}
